package g

import (
	"encoding/json"
	"gitee.com/injoyai/goutil/conv"
	"gitee.com/injoyai/goutil/sort"
)

func newMap(i interface{}) Map {
	m := Map{}
	_ = json.Unmarshal(conv.Bytes(i), &m)
	return m
}

func (this Map) Struct(ptr interface{}) error {
	bs, err := json.Marshal(this)
	if err != nil {
		return err
	}
	return json.Unmarshal(bs, ptr)
}

func (this Map) Unmarshal(ptr interface{}) error { return this.Struct(ptr) }

func (this Map) Json() string { return conv.String(this) }

func (this Map) Bytes() []byte { return conv.Bytes(this) }

func (this Map) GetVar(key string) *conv.Var { return conv.New(this[key]) }

func (this Map) Merge(m Map) Map {
	for key, val := range m {
		this[key] = val
	}
	return this
}

/*



 */

// Clear 清空
func (this *List) Clear() *List {
	*this = List{}
	return this
}

// Set 重新设置
func (this *List) Set(v ...interface{}) *List {
	*this = *this.Clear().Add(v...)
	return this
}

// Add 添加
func (this *List) Add(v ...interface{}) *List {
	for _, k := range v {
		*this = append(*this, conv.Interfaces(k)...)
	}
	return this
}

// Sort 排序,interface{} 版本
func (this *List) Sort(fn func(a, b interface{}) bool) error {
	return sort.New(fn).Bind(this)
}

// SortVar 排序,conv.Var 版本
func (this *List) SortVar(fn func(a, b *conv.Var) bool) error {
	return this.Sort(func(a, b interface{}) bool {
		return fn(conv.New(a), conv.New(b))
	})
}

// SortMap 排序,map 版本
func (this *List) SortMap(key string, desc ...bool) error {
	return sort.SortMap(key, desc...).Bind(this)
}
